package com.aizhixin.lab.project.template.service;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.core.PublicErrorCode;
import com.aizhixin.lab.project.template.core.TaskFileType;
import com.aizhixin.lab.project.template.domain.DeleteDomain;
import com.aizhixin.lab.project.template.domain.ModuleTaskDomain;
import com.aizhixin.lab.project.template.domain.ModuleTaskFileDomain;
import com.aizhixin.lab.project.template.domain.ProjectRoleDomain;
import com.aizhixin.lab.project.template.entity.*;
import com.aizhixin.lab.project.template.repository.ExercisesRepository;
import com.aizhixin.lab.project.template.repository.ModuleTaskRepository;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@Transactional
public class ModuleTaskService {
    @Autowired
    private ModuleTaskRepository taskRepository;
    @Autowired
    private ModuleTaskFileService taskFileService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectModuleService moduleService;
    @Autowired
    private ExercisesRepository exercisesRepository;
    public void updateSort(List<String> ids){
        int i=1;
        for (String id : ids) {
            ModuleTask moduleTask = taskRepository.findByIdAndDeleteFlag(id, DataValidity.VALID.getState());
            moduleTask.setTaskNo(i);
            taskRepository.save(moduleTask);
            i++;
        }
    }
    public String save(ModuleTaskDomain domain) {
        Boolean isNew = false;
        if (null == domain.getId() || "".equals(domain.getId())) {
            domain.setId(UUID.randomUUID().toString());
            isNew = true;
        }
        List<ModuleTaskFile> moduleTaskFileList = new ArrayList<>();
        if (domain.getTaskImages() != null) {
            for (ModuleTaskFileDomain taskFileDomain : domain.getTaskImages()) {
                ModuleTaskFile moduleTaskFile = new ModuleTaskFile();
                BeanUtils.copyProperties(taskFileDomain, moduleTaskFile);
                moduleTaskFile.setTaskId(domain.getId());
                moduleTaskFile.setFileName(taskFileDomain.getFileName());
                moduleTaskFile.setFileUrl(taskFileDomain.getFileUrl());
                moduleTaskFile.setFileType(TaskFileType.image.getIntValue());
                moduleTaskFile.setId(UUID.randomUUID().toString());
                moduleTaskFile.setCreatedDate(new Date());
                moduleTaskFile.setDeleteFlag(DataValidity.VALID.getState());
                moduleTaskFileList.add(moduleTaskFile);
            }
        }
        if (domain.getTeachingMaterial() != null) {
            for (ModuleTaskFileDomain taskFileDomain : domain.getTeachingMaterial()) {
                ModuleTaskFile moduleTaskFile = new ModuleTaskFile();
                BeanUtils.copyProperties(taskFileDomain, moduleTaskFile);
                moduleTaskFile.setTaskId(domain.getId());
                moduleTaskFile.setFileName(taskFileDomain.getFileName());
                moduleTaskFile.setFileUrl(taskFileDomain.getFileUrl());
                moduleTaskFile.setFileType(TaskFileType.teachingMaterial.getIntValue());
                moduleTaskFile.setId(UUID.randomUUID().toString());
                moduleTaskFile.setCreatedDate(new Date());
                moduleTaskFile.setDeleteFlag(DataValidity.VALID.getState());
                moduleTaskFileList.add(moduleTaskFile);
            }
        }
        if (domain.getVideoFileList() != null) {
            for (ModuleTaskFileDomain taskFileDomain : domain.getVideoFileList()) {
                ModuleTaskFile moduleTaskFile = new ModuleTaskFile();
                BeanUtils.copyProperties(taskFileDomain, moduleTaskFile);
                moduleTaskFile.setTaskId(domain.getId());
                moduleTaskFile.setFileName(taskFileDomain.getFileName());
                moduleTaskFile.setFileUrl(taskFileDomain.getFileUrl());
                moduleTaskFile.setFileFirstImg(taskFileDomain.getFileFirstImg());
                moduleTaskFile.setFileType(TaskFileType.taskVideo.getIntValue());
                moduleTaskFile.setId(UUID.randomUUID().toString());
                moduleTaskFile.setCreatedDate(new Date());
                moduleTaskFile.setDeleteFlag(DataValidity.VALID.getState());
                moduleTaskFileList.add(moduleTaskFile);
            }
        }
        List<ProjectRole> projectRoles = new ArrayList<>();
        if (domain.getProjectRoleDomainList() != null) {
            for (ProjectRoleDomain roleDomain : domain.getProjectRoleDomainList()) {
                ProjectRole projectRole = new ProjectRole();
                BeanUtils.copyProperties(roleDomain, projectRole);
                projectRoles.add(projectRole);
            }
        }
        if (isNew) {
            ModuleTask moduleTask = new ModuleTask();
            BeanUtils.copyProperties(domain, moduleTask);
            Integer num = taskRepository.countByModuleIdAndDeleteFlag(domain.getModuleId(), DataValidity.VALID.getState());
            moduleTask.setTaskNo(num+1);
            moduleTask.setProjectRoleList(projectRoles);
            moduleTask.setDeleteFlag(DataValidity.VALID.getState());
            moduleTask.setCreatedDate(new Date());
            moduleTask.setWorkOrderNum(0);
            taskRepository.save(moduleTask);
            taskFileService.save(moduleTaskFileList);
            ProjectModule projectModule = moduleService.findById(moduleTask.getModuleId());
            if (!Objects.isNull(projectModule)) {
                projectModule.setTaskNum(projectModule.getTaskNum()+1);
                moduleService.save(projectModule);
            }
            Project project = projectService.findProject(projectModule.getProjectId());
            if (!Objects.isNull(project)) {
                project.setTaskNum(project.getTaskNum()==null?0:project.getTaskNum()+1);
                projectService.save(project);
            }
            return moduleTask.getId();
        }
        ModuleTask one = taskRepository.findOne(domain.getId());
        domain.setWorkOrderNum(one.getWorkOrderNum());
        BeanUtils.copyProperties(domain, one);
        one.setProjectRoleList(projectRoles);
        taskRepository.save(one);
        taskFileService.deleteByTaskId(one.getId());
        taskFileService.save(moduleTaskFileList);
        return domain.getId();
    }

    public List<ModuleTaskDomain> findTaskByModuleId(String id) {
        List<ModuleTask> taskList = taskRepository.findByModuleIdAndDeleteFlagOrderByTaskNoAsc(id, DataValidity.VALID.getState());
        List<ModuleTaskDomain> taskDomainList = new ArrayList<>();
        for (ModuleTask moduleTask : taskList) {
            ModuleTaskDomain moduleTaskDomain = new ModuleTaskDomain();
            BeanUtils.copyProperties(moduleTask, moduleTaskDomain);
            List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
            for (ProjectRole projectRole : moduleTask.getProjectRoleList()) {
                ProjectRoleDomain roleDomain = new ProjectRoleDomain();
                BeanUtils.copyProperties(projectRole, roleDomain);
                roleDomainList.add(roleDomain);
            }
            Integer count = exercisesRepository.countByTaskId(moduleTaskDomain.getId());
            if (count>0){
                moduleTaskDomain.setIsExist(true);
            }else {
                moduleTaskDomain.setIsExist(false);
            }
            moduleTaskDomain.setProjectRoleDomainList(roleDomainList);
            taskDomainList.add(moduleTaskDomain);
        }
        return taskDomainList;
    }

    public ModuleTaskDomain findTaskInfo(String id) {
        ModuleTask task = taskRepository.findOne(id);
        ModuleTaskDomain moduleTaskDomain = new ModuleTaskDomain();
        BeanUtils.copyProperties(task, moduleTaskDomain);
        List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
        List<ModuleTaskFileDomain> taskImages = new ArrayList<>();
        List<ModuleTaskFileDomain> teachingMaterial = new ArrayList<>();
        List<ModuleTaskFileDomain> videoFileList = new ArrayList<>();
        for (ProjectRole projectRole : task.getProjectRoleList()) {
            ProjectRoleDomain roleDomain = new ProjectRoleDomain();
            BeanUtils.copyProperties(projectRole, roleDomain);
            roleDomainList.add(roleDomain);
        }
        moduleTaskDomain.setProjectRoleDomainList(roleDomainList);

        for (ModuleTaskFile moduleTaskFile : taskFileService.findTaskFile(task.getId())) {
            ModuleTaskFileDomain domain = new ModuleTaskFileDomain();
            BeanUtils.copyProperties(moduleTaskFile, domain);

            if (TaskFileType.image.getIntValue().equals(moduleTaskFile.getFileType())) {
                taskImages.add(domain);
            } else if (TaskFileType.teachingMaterial.getIntValue().equals(moduleTaskFile.getFileType())) {
                teachingMaterial.add(domain);
            } else {
                videoFileList.add(domain);
            }
        }
        moduleTaskDomain.setVideoFileList(videoFileList);
        moduleTaskDomain.setTaskImages(taskImages);
        moduleTaskDomain.setTeachingMaterial(teachingMaterial);
        return moduleTaskDomain;
    }

    public Integer countTaskNum(String moduleId) {
        return taskRepository.countByModuleIdAndDeleteFlag(moduleId, DataValidity.VALID.getState());
    }

    public Map<String, Object> delete(DeleteDomain deleteDomain) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer workOrderNum = workOrderService.countWorkOrder(deleteDomain.getId());
        if (workOrderNum > 0) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "请先删除子任务");
        } else {
            ModuleTask moduleTask = taskRepository.findOne(deleteDomain.getId());
            if (!Objects.isNull(moduleTask)) {
                Project project = projectService.findProject(deleteDomain.getProjectId());
                moduleTask.setDeleteFlag(DataValidity.INVALID.getState());
                taskRepository.save(moduleTask);
                Integer num = taskRepository.countByModuleIdAndDeleteFlag(moduleTask.getModuleId(),DataValidity.VALID.getState());
                if (!Objects.isNull(project)) {
                    project.setTaskNum(project.getTaskNum()-1);
                    projectService.save(project);
                    updateSort(moduleTask.getModuleId());

                }
                ProjectModule projectModule = moduleService.findById(moduleTask.getModuleId());
                if (!Objects.isNull(projectModule)) {
                    projectModule.setTaskNum(num);
                    moduleService.save(projectModule);
                }
                result.put(ApiReturnConstants.SUCCESS, true);
                result.put(ApiReturnConstants.DATA, "删除成功");
            }else {
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.MESSAGE, "未找到任务");
            }
        }
        return result;
    }

    public void updateSort(String moduleId) {
        List<ModuleTask> moduleTaskList = taskRepository.findByModuleIdAndDeleteFlagOrderByTaskNoAsc(moduleId, DataValidity.VALID.getState());
        for (int i = 0; i < moduleTaskList.size(); i++) {
            moduleTaskList.get(i).setTaskNo(i + 1);
        }
        taskRepository.save(moduleTaskList);
    }
}
